package;
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;
import flash.events.Event;
import flash.display.Shape;
import flash.display.Sprite;
import flash.net.NetConnection;
import flash.net.Responder;
import flash.Lib;

typedef BulletData =
{
	var id : Int;
	var name : String;
	var x : Float;
	var y : Float;
	var rotation : Float;
	var health : Float;
}
class Bullet extends Sprite
{
	public var data:BulletData;
	private var s : Shape;
	private var controller : BulletControl;
	
	public function new(data:BulletData, control:Bool)
	{
		super();
		s = new Shape();
		addChild(s);
		draw(control);
		setData(data);
		if(control)
			controller = new BulletControl(this);
	}
	public function cleanup()
	{
		controller.cleanup();
		controller = null;
		data = null;
		s.graphics.clear();
	}
	function draw(control)
	{
		s.graphics.clear();
		s.graphics.beginFill(control?0xFF0000:0x000000, 1);
		s.graphics.drawCircle(4,4,4);
		s.graphics.endFill();
		s.x = s.y = -4;
	}
	public function setData(d:BulletData)
	{
		d.x += 30 * Math.sin(d.rotation * (Math.PI / 180));
		d.y -= 30 * Math.cos(d.rotation * (Math.PI / 180));
		
		this.data = d;
		name = d.name;
		rotation = d.rotation;
		x = d.x;
		y = d.y;
		
	}
}
class BulletControl
{
	var bullet : Bullet;
	var speed : Float;
	public function new(b:Bullet)
	{
		bullet = b;
		speed = 10.0;
		setEnabled(true);
	}
	public function cleanup()
	{
		setEnabled(false);
		bullet = null;
	}
	public function setEnabled(value:Bool):Void
	{
		if(value)
		{
			Lib.current.stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
		}
		else
		{
			Lib.current.stage.removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
		}
	}
	private function enterFrameHandler(event:Event):Void
	{
		bullet.data.y -= speed * Math.cos(bullet.data.rotation * (Math.PI / 180));
		bullet.data.x += speed * Math.sin(bullet.data.rotation * (Math.PI / 180));
			bullet.dispatchEvent(new Event("move"));
		if(bullet.data.y < 0 || bullet.data.y > 600 || bullet.data.x < 0 || bullet.data.x > 800)
			bullet.dispatchEvent(new Event("leave"));
	}
}